package com.zhima.util;

import cn.hutool.core.util.RuntimeUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 芝麻
 * @date : 2023-08-06 16:30
 **/
public class SystemCommandUtil {
    /**
     * 同时执行多条命令
     *
     * @param commands
     * @return
     */
    public static List<String> execForResults(String... commands) {
        return RuntimeUtil.execForLines(buildCommandTogether(commands));
    }

    /**
     * 同时执行多条命令
     *
     * @param commands
     * @return
     */
    public static String buildCommandTogether(String... commands) {
        StringBuilder stringBuilder = new StringBuilder("cmd /c ");
        for (int i = 0; i < commands.length; i++) {
            stringBuilder.append(commands[i]);
            if (i != commands.length - 1) {
                stringBuilder.append(" && ");
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 同时执行多条命令，并且将inputDatas作为输入数据输入终端
     *
     * @param inputDatas
     * @param commands
     * @return
     */
    public static List<String> execForResults(List<String> inputDatas, String... commands) {
        List<String> ans = new ArrayList<>();
        String commandTogether = buildCommandTogether(commands);
        Process process = RuntimeUtil.exec(commandTogether);
        try (
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
        ) {
            for (String inputData : inputDatas) {
                bw.write(inputData);
                bw.write('\n');
            }
            bw.flush();
            String line;
            while ((line = br.readLine()) != null) {
                ans.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ans;
    }
}
